const express = require('express');
const fs = require('fs');
const app = express();
const http = require('http');
const multer = require('multer')
const server = http.createServer(app);
const path = require('path');

const storage = multer.diskStorage({
  destination(req, file, cb) {
    cb(null, './build')
  },
  filename(req, file, cb) {
    cb(null, file.originalname)
  }
})

const { Server } = require("socket.io");
const upload = multer({ storage })
const io = new Server(server, { cors: true });

app.use(express.static(path.join(__dirname, "build")));

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/login.html');
});

app.post('/upload', upload.single('file'), (req, res) => {
  res.end('上传成功')
});

io.on('connection', (socket) => {
  console.log('connection');
  socket.on('login', (anotherSocketId, values) => {
    const files = fs.readFileSync(path.join(__dirname, '/db/user.json'), 'utf-8')
    const userList = JSON.parse(files).userList
    const data = userList.filter(item => item.username === values.username)
    if (data.length > 0) {
      if (data[0].password === values.password) {
        io.to(anotherSocketId).emit('login back', { message: '登录成功', stutes: true, username: values.username });
        socket.username = values.username
        io.emit('sb register', userList.map(item => {
          if (item.username === values.username) {
            item.status = 2
          }
          return { name: item.username, status: item.status, imgUrl: item.imgUrl }
        }));
        io.emit('send message', { isSystem: true, message: values.username + '#' + '加入了房间' });
        fs.writeFileSync(path.join(__dirname, '/db/user.json'), JSON.stringify({ userList }), 'utf8')
      } else {
        io.to(anotherSocketId).emit('login back', { message: '密码不正确', stutes: false });
      }
    } else {
      io.to(anotherSocketId).emit('login back', { message: '该用户名未注册或已被清除', stutes: false });
    }

  });

  socket.on('register', (anotherSocketId, values) => {
    const files = fs.readFileSync(path.join(__dirname, '/db/user.json'), 'utf-8')
    const userList = JSON.parse(files).userList
    if (userList.some(item => item.username == values.username)) {
      io.to(anotherSocketId).emit('register back', { message: '用户名已经存在', stutes: false });
    } else {
      userList.push({
        ...values,
        status: 1,
        imgUrl: values.imgUrl || 'https://picx.zhimg.com/80/v2-c68994dabc5554576e89b8dc376fbb66_720w.webp?source=1940ef5c'
      });
      socket.imgUrl = values.imgUrl || 'https://picx.zhimg.com/80/v2-c68994dabc5554576e89b8dc376fbb66_720w.webp?source=1940ef5c'
      fs.writeFileSync(path.join(__dirname, '/db/user.json'), JSON.stringify({ userList }), 'utf8')
      io.to(anotherSocketId).emit('register back', { message: '注册成功', stutes: true });
      io.emit('sb register', userList.map(item => {
        return { name: item.username, status: item.status, imgUrl: item.imgUrl }
      }));
    }
  })

  socket.on('self send message', (msg) => {
    io.emit('send message', {
      isSystem: false,
      message: msg.content,
      name: msg.username,
      imgUrl: socket.imgUrl
    });
  });

  socket.on('disconnect', () => {
    const files = fs.readFileSync(path.join(__dirname, '/db/user.json'), 'utf-8')
    const userList = JSON.parse(files).userList
    io.emit('send message', {
      isSystem: true,
      message: socket?.username ?
        socket?.username + '#' + '离开了房间' :
        '有人默默取消了登录'
    });
    if (!socket?.username) return
    io.emit('sb register', userList.map(item => {
      if (item.username === socket?.username) {
        item.status = 1
      }
      return { name: item.username, status: item.status, imgUrl: item.imgUrl }
    }));
    fs.writeFileSync(path.join(__dirname, '/db/user.json'), JSON.stringify({ userList }), 'utf8')
  });
})

server.listen(80, () => {
  console.log('listening on *:80');
});

